﻿using APPWG4806.Back.Entry;
using APPWG4806.Haper;
using APPWG4806.Helper;
using APPWG4806.View;
using DevExpress.CodeParser;
using DevExpress.DataAccess.ObjectBinding;
using DevExpress.XtraPrinting.BarCode;
using DevExpress.XtraRichEdit.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WebCarLine.Common;
using DataTableExtensions = APPWG4806.Helper.DataTableExtensions;

namespace APPWG4806
{
    public partial class Form132 : Form
    {
        public MaterialEntry Data { get; set; }

        public Form132()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
            // 登录信息
            UserId_TB.Text = LoginUserForm.userInfo.LoginId;
            this.FormClosing += new FormClosingEventHandler(MyForm_FormClosing);
        }

        private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void process_ComBoBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (process_ComBoBox.SelectedIndex != -1)
            {
                Console.WriteLine(process_ComBoBox.SelectedValue);
                Console.WriteLine(process_ComBoBox.SelectedText);
                flowLayoutPanel1.Controls.Clear();

                #region 数据库查询数据
                // 执行SQL操作，按照工序ID查询相关信息
                //string sqlStr = "SELECT [l].[ID], [l].[CodeLength], [l].[ComponentName], [l].[ComponentSeq], [l].[ComponentTypeId], " +
                //    "[l].[Condtion], [l].[CreateDate], [l].[Creator], [l].[Description], [l].[IsClear], [l].[KeyCode], [l].[KeyCodeIndex]," +
                //    " [l].[MaterialId], [l].[Modifier], [l].[ModifyDate], [l].[OrderQtyControl], [l].[RepeatCodeNumber], [l].[WorkStationIndex]" +
                //    " FROM [LH_Component] AS [l] where [l].[WorkStationIndex] = @WorkStationId ORDER BY [l].[ComponentSeq]";
                //List<SqlParameter> sqlParameters = new List<SqlParameter> {
                //    new SqlParameter("@WorkStationId", SqlDbType.VarChar) { Value = process_ComBoBox.SelectedValue }
                //};
                //DataTable data = DatabaseHelper.ExecuteQuery(sqlStr, sqlParameters);
                #endregion

                #region 远程调用API数据
                List<ComponentEntry> components = new List<ComponentEntry>();
                try
                {
                    string json = HttpHelp.GetData("http://localhost:9081/LH_ListApi/GetComponentList?workStationId=" + process_ComBoBox.SelectedValue,null);
                    components = JsonConvert.DeserializeObject<List<ComponentEntry>>(json);
                }
                catch (Exception) {
                    MessageBox.Show("API连接错误");
                    return;
                }
                #endregion
                int preBatchQtyNum = int.Parse(PreBatchQty_TB.Text);
                if (preBatchQtyNum > 0)
                {
                    BatchQty_TB.Text =  preBatchQtyNum.ToString();
                }
                else
                {
                    string sn = MaterialNo_Tb.Text.Trim();
                    string json = preBatchQtyNum.ToString();
                    try
                    {
                        json = HttpHelp.GetData("http://localhost:9081/LH_ListApi/GetPreWorkstaionScannerCount?workstationId="+process_ComBoBox.SelectedValue+"&sn="+sn, null);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("API连接失败");
                        return;
                    }
                    BatchQty_TB.Text = json;
                }

                WorkStationEntry entry = (WorkStationEntry)process_ComBoBox.SelectedItem;
                IsPrint_CB.Checked = entry.IsPrint;
                IsCheck_CB.Checked = entry.IsCheck;
                LastWorkStation_CB.Checked = entry.LastWorkStation;

                K3MaterialNo_TB.Text = entry.MachineNo;
                IsCheckPo_CB.Checked= entry.IsCheckPo;

                

                if (components.Count != 0)
                //if (data.Rows.Count != 0)
                {
                    Console.WriteLine("DataTable is empty.");
                    //List<ComponentEntry> components = DataTableExtensions.ToList<ComponentEntry>(data);
                    for (int i = 0; i < components.Count; i++)
                    {
                        Panel panel = new TableLayoutPanel();
                        System.Windows.Forms.Label label = new System.Windows.Forms.Label();
                        label.Text = components[i].ComponentName;
                        panel.Controls.Add(label);
                        TextBox textBox = new TextBox();
                        textBox.Text = "请输入" + label.Text; // 初始为空
                        textBox.ForeColor = SystemColors.GrayText; // 提示文本的颜色
                        textBox.Tag = "请输入"+label.Text; // 存储提示文本
                        textBox.Enter += TextBox_Enter;
                        textBox.Leave += TextBox_Leave;
                        textBox.KeyDown += TextBox_KeyDown;
                        textBox.Name = components[i].ID.ToString();
                        panel.Controls.Add(label);
                        panel.Controls.Add(textBox);
                        flowLayoutPanel1.AutoScroll = true;
                        flowLayoutPanel1.BorderStyle = BorderStyle.None;
                        flowLayoutPanel1.Controls.Add(panel);
                    }
                    flowLayoutPanel1.Visible = true;
                }
                else
                {
                    flowLayoutPanel1.Controls.Clear();
                    flowLayoutPanel1.Visible = false;
                    Console.WriteLine("DataTable is not empty.");
                }
                
            }
        }

        private void TextBox_KeyDown(Object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextBox text = (TextBox)sender;
                if (text.Text == text.Tag.ToString() || string.IsNullOrWhiteSpace(text.Text))
                {
                    MessageBox.Show("子件" + text.Text + "Sn不可为空");
                    return;
                }
                string res = ChickChildSn(text.Name,text.Text);
                if (res != "ok")
                {
                    text.Text = "";
                    MessageBox.Show(res);
                    return;
                }
            }
        }


        private void TextBox_Enter(object sender, EventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (textBox != null && textBox.Text == textBox.Tag.ToString())
            {
                textBox.Text = ""; // 清空文本
                textBox.ForeColor = SystemColors.WindowText; // 输入文本的颜色
            }
        }

        private void TextBox_Leave(object sender, EventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (textBox != null && textBox.Text == "")
            {
                textBox.Text = textBox.Tag.ToString(); // 显示提示文本
                textBox.ForeColor = SystemColors.GrayText; // 提示文本的颜色
            }
        }

        private void Form132_Load(object sender, EventArgs e)
        {
            process_ComBoBox.DropDownStyle = ComboBoxStyle.DropDownList;
            
        }

      
        /// <summary>
        /// 回车打开物料查询所有有效物料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                MaterialQueryForm xtraForm = new MaterialQueryForm(this);
                xtraForm.ShowDialog();
                if (Data==null)
                {
                    return;
                }
                flowLayoutPanel1.Controls.Clear();
                flowLayoutPanel1.Visible = false;

                MaterialNo_Tb.Text = Data.MaterialNo;
                BatchQty_TB.Text = Data.BatchQty.ToString();
                Color_TB.Text = Data.Color;
                IsCheck_CB.Checked = Data.IsCheck;
                IsPrint_CB.Checked = Data.IsPrint;
                LastWorkStation_CB.Checked = Data.LastWorkStation;
                MaterialSpec_TB.Text = Data.MaterialSpec;
                OutDiameter_TB.Text = Data.OutDiameter;
                WorkStationTypeName_TB.Text = Data.WorkStationTypeName;
                WorkStationVersion_TB.Text = Data.WorkStationVersion;
                

                #region 数据库查询
                //List<Parameter> parameters = new List<Parameter>();
                //string sql = "SELECT [l].[IdIndex],  [l].[BatchQty],  [l].[CheckTimeA],  [l].[CheckTimeB],  [l].[CheckTimeC],  [l].[CheckTimeD],  [l].[Condtion],  [l].[ControlBackStation]," +
                //    "  [l].[ControlBackTime],  [l].[CreateDate],  [l].[Creator],  [l].[Description],  [l].[IsCheck],  [l].[IsCheckPo],  [l].[IsPrint],  [l].[LastWorkStation],  [l].[MachineNo]," +
                //    "  [l].[MaterialId],  [l].[MaterialNo],  [l].[Modifier],  [l].[ModifyDate],  [l].[SnKey],  [l].[SnKeyIndex],  [l].[SnKeyLength],  [l].[UserDo],  [l].[WeldingProjectName], " +
                //    " [l].[WorkStationName],  [l].[WorkStationSeq],  [l].[WorkStationTypeId],  [l].[WorkStationVersion] FROM  " +
                //    "[LH_WorkStation] AS [l] WHERE  [l].[WorkStationVersion] = '"+Data.WorkStationVersion+"'  AND [l].[MaterialId] = "+Data.MaterialId+"  AND [l].[Condtion] = CAST ( 0 AS BIT ) ORDER BY  [l].[WorkStationSeq]";
                //DataTable dataTable = DatabaseHelper.ExecuteQuery(sql);
                //List<WorkStationEntry> workStationListEntries = Helper.DataTableExtensions.ToList<WorkStationEntry>(dataTable);
                #endregion

                #region 调用远程API查询
                List<WorkStationEntry> workStationListEntries = new List<WorkStationEntry>();
                try
                {
                    string json = HttpHelp.GetData("http://localhost:9081/LH_ListApi/GetWorkstationListByMateiralIdLoginId?materialId="+Data.MaterialId+ "&workstationVersion="+Data.WorkStationVersion+"&userLoginId="+LoginUserForm.userInfo.LoginId, null);
                    workStationListEntries = JsonConvert.DeserializeObject<List<WorkStationEntry>>(json);
                }
                catch (Exception)
                {
                    MessageBox.Show("API连接错误");
                    return;
                }
                #endregion


                // 禁用修改选项事件，以避免在设置项时触发事件
                process_ComBoBox.SelectedIndexChanged -= process_ComBoBox_SelectedIndexChanged;

                process_ComBoBox.DataSource = workStationListEntries;
                process_ComBoBox.DisplayMember = "WorkStationName";
                process_ComBoBox.ValueMember = "IdIndex";
                process_ComBoBox.SelectedIndex = -1;

                // 启用修改选项事件
                process_ComBoBox.SelectedIndexChanged += process_ComBoBox_SelectedIndexChanged;
                
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 生成SN条码校验
            string materialNo = MaterialNo_Tb.Text.Trim();
            if (string.IsNullOrWhiteSpace(materialNo))
            {
                MessageBox.Show("物料不可以为空", "提示");
                return;
            }

            if (process_ComBoBox.SelectedIndex<0)
            {
                MessageBox.Show("工序不可以为空", "提示");
                return ;
            }
            string workstationId = process_ComBoBox.SelectedValue.ToString();

            string batchQty = BatchQty_TB.Text.Trim();
            if (string.IsNullOrWhiteSpace(batchQty))
            {
                MessageBox.Show("批次数量错误 不可为0与空", "提示");
                return ;
            }
            try
            {
                string json = HttpHelp.GetData("http://localhost:9081/LH_ListApi/CreateSn?materialNo="+materialNo+"&batchQty="+batchQty+"&workstationId="+workstationId, null);
                SnCode_TB.Text = json;
            }
            catch (Exception)
            {
                MessageBox.Show("API连接失败");
                return ;
            }
        }


        /// <summary>
        /// 打印预览点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PrintShow_BT_Click(object sender, EventArgs e)
        {
            string snCode = SnCode_TB.Text;
            if (string.IsNullOrWhiteSpace(snCode))
            {
                MessageBox.Show("SN条码不能为空");
                return;
            }
            foreach (Control container in flowLayoutPanel1.Controls)
            {
                if (container is Panel panel)
                {
                    // 遍历Panel中的控件
                    foreach (Control ctrl in panel.Controls)
                    {
                        // 检查是否是TextBox控件且不为空
                        if (ctrl is TextBox textBox)
                        {
                            if (string.IsNullOrEmpty(textBox.Text)||textBox.Text.Contains("请输入"))
                            {
                                MessageBox.Show("子件SN不可为空");
                                return ; // 如果找到非空的TextBox，返回false
                            }
                            string componentId = textBox.Name;
                            string sn = textBox.Text;
                            string res = ChickChildSn(componentId, sn);
                            if (res != "ok")
                            {
                                MessageBox.Show(res);
                                return ;
                            }

                            //TODO 校验子件 物料与k3中的物料
                            //TODO 校验子件 数量
                        }
                    }
                }
            }
            


            // 设置二维码的配置选项
            var options = new ZXing.QrCode.QrCodeEncodingOptions
            {
                Width = 250,
                Height = 250,
                Margin = 1, // 二维码边缘空白区域
                ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.M // 错误校正级别
            };
            // 创建二维码生成器
            var writer = new ZXing.BarcodeWriter
            {
                Format = ZXing.BarcodeFormat.QR_CODE,
                Options = options
            };
            // 生成二维码
            Bitmap codeBit = writer.Write(snCode);
            
            BarQRCodeForm barQRCode = new BarQRCodeForm(codeBit);
            barQRCode.ShowDialog();
        }
        /// <summary>
        /// 子件校验
        /// </summary>
        /// <param name="componentId"></param>
        /// <param name="sn"></param>
        /// <returns></returns>
        public string ChickChildSn(string componentId,string sn)
        {
            string res = "ok";
            try
            {
                //校验子件是组件类型 判定该物料工序是否已经完工
                res = HttpHelp.GetData("http://localhost:9081/LH_ListApi/CheckComponentStatus?componentId=" + componentId + "&sn=" + sn, null);
                JObject jsonObject = JObject.Parse(res);
                if (jsonObject["Message"].ToString() != "ok")
                {
                    return jsonObject["Message"].ToString();
                }
            }
            catch (Exception)
            {
                res = "API连接失败";
            }
            try
            {
                //校验子键条码的合法性
                res = HttpHelp.GetData("http://localhost:9081/LH_Component/CheckItemSn?componentId=" + componentId + "&itemSn=" + sn, null);
                if (res != "ok")
                {
                    return res;
                }
            }
            catch (Exception)
            {
                res = "API连接失败";
            }
            return res;
        }


        /// <summary>
        /// 不良汇报按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BadReport_BT_Click(object sender, EventArgs e)
        {
            BadReportForm badReportForm = new BadReportForm();
            badReportForm.ShowDialog();
        }

        private void IsPrint_CB_CheckedChanged(object sender, EventArgs e)
        {
            if (IsPrint_CB.Checked)
            {
                CreateCode_BT.Enabled = true;
                PrintShow_BT.Enabled = true;
                SnCode_TB.Enabled = false;
            }
            else
            {
                CreateCode_BT.Enabled = false;
                PrintShow_BT.Enabled = false;
                SnCode_TB.Enabled = true;
            }
        }
    }
}
